package com.peng.leetcode.list;

/**
 * AddTwoNumbers
 *
 * @author: lupeng6
 * @create: 2021/1/1 19:55
 */
public class AddTwoNumbers {

    public static void main(String[] args) {

    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int prev = 0;
        ListNode sentinel = new ListNode(-1);
        ListNode current = sentinel;
        while (l1 != null || l2 != null) {
            ListNode temp = new ListNode(0);

            int sum = 0;
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            sum += prev;

            if (sum >= 10) {
                prev = sum / 10;
                temp.val = sum % 10;
            } else {
                prev = 0;
                temp.val = sum;
            }
            current.next = temp;
            current = current.next;
        }

        if (prev != 0) {
            current.next = new ListNode(prev);
        }

        return sentinel.next;
    }
}
